package com.chuantou.yuba.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.chuantou.yuba.db.columns.MessageColumns;
import com.chuantou.yuba.db.util.SqliteWrapper;
import com.chuantou.yuba.pojo.Message;

public class MessageDao {
	public static final List<Message> readAllMessage(Context context) {
		Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(), MessageColumns.CONTENT_URI, null, null, null, MessageColumns._ID + " desc");
		List<Message> messages = new ArrayList<Message>();
		if (cursor != null) {
			while (cursor.moveToNext()) {
				Message message = readMessageFromCursor(cursor);
				messages.add(message);
			}
		}
		return messages;
	}

	public static final int deleteMessage(Context context, String id) {
		return SqliteWrapper.delete(context, context.getContentResolver(), MessageColumns.CONTENT_URI, MessageColumns._ID + "=?", new String[] { id });
	}

	public static final void insertMessage(Context context, String msgId, String action, String message, long time) {
		ContentValues values = new ContentValues();

		values.put(MessageColumns.COLUMN_ACTION, action);
		values.put(MessageColumns.COLUMN_MESSAGE, message);
		values.put(MessageColumns.COLUMN_TIME, time);
		SqliteWrapper.insert(context, context.getContentResolver(), MessageColumns.CONTENT_URI, values);
	}

	private static final Message readMessageFromCursor(Cursor cursor) {
		Message message = new Message();
		message.setAction(cursor.getString(cursor.getColumnIndex(MessageColumns.COLUMN_ACTION)));
		message.setId(cursor.getString(cursor.getColumnIndex(MessageColumns._ID)));
		message.setMessage(cursor.getString(cursor.getColumnIndex(MessageColumns.COLUMN_MESSAGE)));
		message.setTime(cursor.getLong(cursor.getColumnIndex(MessageColumns.COLUMN_TIME)));
		return message;
	}
}
